package com.weirdor.elasticsearch.kit;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.index.query.*;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by weirdor on 2017/12/19.
 *  文件描述:方便增删查改
 */
public class ElasticSearchQuery {

    private String TypeName;

    private  String IndexName;

    /*用于记录单挑插入时的id*/
    private String id;

    private JSONObject jsonObject = new JSONObject();

    private List<QueryBuilder> queryBuilderList=new ArrayList<>();

    public ElasticSearchQuery use(String TypeName, String IndexName) {
        this.TypeName = TypeName;
        this.IndexName= IndexName;
        return this;
    }


    public ElasticSearchQuery set(String key, Object value) {
        if (ElasticSearchJsonObjectKit.conversionValidation(value)) {
            jsonObject.put(key, ElasticSearchJsonObjectKit.toJsonObject(value));
        }else {
            jsonObject.put(key, value);
        }
        return this;
    }

    public  ElasticSearchQuery set(Object object){
        jsonObject=ElasticSearchJsonObjectKit.toJsonObject(object);
        return this;
    }

    public ElasticSearchQuery eq(String field,String value){
        queryBuilderList.add(QueryBuilders.termQuery(field,value));
        return  this;
    }

    public ElasticSearchQuery match(String field,String value){
        queryBuilderList.add(QueryBuilders.matchQuery(field,value));
        return  this;
    }

    public ElasticSearchQuery matchPhrase(String field,String value){
        queryBuilderList.add(QueryBuilders.matchPhraseQuery(field,value));
        return  this;
    }
    public ElasticSearchQuery prefix(String field,String value){
        queryBuilderList.add(QueryBuilders.prefixQuery(field, value).rewrite("top_terms_256"));
        return  this;
    }

    public String save() {
       return  ElasticSearchKit.insert(IndexName,TypeName,id,jsonObject);
    }

    public String update(){
        return  ElasticSearchKit.update(IndexName,TypeName,id,jsonObject);
    }
    public String deleteOne(){
        return ElasticSearchKit.delete(IndexName,TypeName,queryBuilderList);
    }
    public  String update(String script){
        return  ElasticSearchKit.update(IndexName,TypeName,id,script);
    }
    public String delete(){
        return ElasticSearchKit.delete(IndexName,TypeName,id);
    }

    public ElasticSearchQuery byId(String Id) {
        this.id=Id;
        return this;
    }
}
